<template>
  <el-cascader :key="key" v-model="areaCodes" :options="cascaderOptions" :props="areaCodeSelectProps" :show-all-levels="false" placeholder="请选择地区" clearable></el-cascader>
</template>

<script>
import { areaList, arealocal } from "@/api/system/area";
import { nextTick } from "process";

export default {
  props: {
    value: [String]
  },
  data() {
    return {
      key: 0,
      areaCodes: [],
      cascaderOptions: [],
      areaCodeSelectProps: {
        lazy: true,
        checkStrictly: true,
        lazyLoad: async (node, resolve)=>{
          var v = await this.loadOption(node.value)
          if(!v){
            node.data.leaf =true;
          }
          resolve(v)
        }
      }
    };
  },
  watch: {
    value: {
      async handler(val) {
        if (val) {
          if(this.areaCodes.length > 0 && this.areaCodes[this.areaCodes.length -1] == val){
            //与现有选择相等。跳过处理
            return
          }
          arealocal(val).then(response => {
            if(response.data && response.data.length > 0){
                this.key++
                nextTick(()=>{
                  this.areaCodes = response.data  
                })
            }
          });
        } else {
          this.areaCodes = [];
        }
      },
      deep: true,
      immediate: true
    },
    areaCodes: {
      async handler(val) {
        if (val && val.length > 0) {
          this.$emit("input", val[val.length - 1])
        } else {
          this.$emit("input", null)
        }
      },
    }
  },
  methods: {
    async loadOption(areaCode) {
      return new Promise((resolve,reject) =>{
        areaList(areaCode ? areaCode : "100000").then(response => {
            if(response.data.length == 0){
              resolve(null)
            } else {
              resolve(response.data.map(item=>({
                key: item.code,
                value: item.code,
                label: item.name,
                leaf: false
              })));
            }
          })
      })
    }
  }
};
</script>